#!/usr/bin/env python3
"""
调试零数据问题的脚本
"""

from database_server_adapter import DatabaseServerAdapter
from table_schema import Column, ColumnType
import traceback

def debug_zero_data_issue():
    """调试为什么统计数据都是0"""
    
    print("🔍 调试零数据问题")
    print("=" * 50)
    
    adapter = DatabaseServerAdapter(data_root="./debug_data")
    
    try:
        # 1. 认证
        print("1. 用户认证...")
        auth_success = adapter.login("root", "root12345")
        print(f"   认证结果: {auth_success}")
        
        if not auth_success:
            print("❌ 认证失败，停止调试")
            return
        
        # 2. 创建数据库
        print("\n2. 创建数据库...")
        db_created = adapter.create_database("debug_db")
        print(f"   数据库创建结果: {db_created}")
        
        # 3. 使用数据库
        print("\n3. 切换数据库...")
        use_success = adapter.use_database("debug_db")
        print(f"   数据库切换结果: {use_success}")
        print(f"   当前数据库: {adapter.get_current_database()}")
        
        # 4. 创建表
        print("\n4. 创建测试表...")
        columns = [
            Column(name="id", column_type=ColumnType.INT, primary_key=True),
            Column(name="name", column_type=ColumnType.VARCHAR, length=50),
            Column(name="value", column_type=ColumnType.INT)
        ]
        table_created = adapter.create_table("test_table", columns)
        print(f"   表创建结果: {table_created}")
        
        # 5. 检查表列表
        print("\n5. 检查表列表...")
        tables = adapter.list_tables()
        print(f"   表列表: {tables}")
        
        # 6. 插入数据
        print("\n6. 插入测试数据...")
        test_records = [
            {"id": 1, "name": "test1", "value": 100},
            {"id": 2, "name": "test2", "value": 200},
            {"id": 3, "name": "test3", "value": 300}
        ]
        
        for i, record in enumerate(test_records):
            result = adapter.insert_record("test_table", record)
            print(f"   插入记录 {i+1}: {result}")
        
        # 7. 检查数据是否真的插入了
        print("\n7. 查询插入的数据...")
        all_records = adapter.select_records("test_table")
        print(f"   查询到的记录数: {len(all_records)}")
        for record in all_records:
            print(f"     {record}")
        
        # 8. 测试表信息获取
        print("\n8. 获取表信息...")
        try:
            table_info = adapter.get_table_info("test_table")
            print(f"   表信息: {table_info}")
        except Exception as e:
            print(f"   表信息获取失败: {e}")
            traceback.print_exc()
        
        # 9. 测试统计信息获取
        print("\n9. 获取表统计信息...")
        try:
            stats = adapter.get_table_statistics("test_table")
            print(f"   统计信息: {stats}")
            
            # 逐步检查统计信息的获取过程
            print("\n   详细调试:")
            print(f"     当前数据库: {adapter.current_database}")
            print(f"     会话ID: {adapter.session_id}")
            print(f"     认证状态: {adapter.is_user_authenticated()}")
            
        except Exception as e:
            print(f"   统计信息获取失败: {e}")
            traceback.print_exc()
        
        # 10. 测试性能统计
        print("\n10. 获取性能统计...")
        try:
            perf_stats = adapter.get_performance_stats()
            print(f"    性能统计: {perf_stats}")
        except Exception as e:
            print(f"    性能统计获取失败: {e}")
            traceback.print_exc()
        
        # 11. 测试索引信息
        print("\n11. 获取索引信息...")
        try:
            index_info = adapter.get_index_info("test_table")
            print(f"    索引信息: {index_info}")
        except Exception as e:
            print(f"    索引信息获取失败: {e}")
            traceback.print_exc()
        
        # 12. 检查数据库引擎状态
        print("\n12. 检查底层引擎状态...")
        try:
            # 直接访问数据库服务器来检查状态
            engine = adapter.database_server.get_database_engine(adapter.session_id, adapter.current_database)
            if engine:
                print(f"    引擎存在: True")
                print(f"    引擎类型: {type(engine)}")
                
                # 检查表页面信息
                if hasattr(engine, 'table_pages'):
                    print(f"    表页面映射: {engine.table_pages}")
                else:
                    print(f"    引擎没有table_pages属性")
                    
                # 检查存储引擎
                if hasattr(engine, 'storage_engine'):
                    storage = engine.storage_engine
                    print(f"    存储引擎类型: {type(storage)}")
                else:
                    print(f"    引擎没有storage_engine属性")
            else:
                print(f"    引擎不存在")
        except Exception as e:
            print(f"    引擎检查失败: {e}")
            traceback.print_exc()
        
    except Exception as e:
        print(f"❌ 调试过程中发生错误: {e}")
        traceback.print_exc()
    finally:
        print("\n🔚 关闭连接...")
        adapter.close()

if __name__ == "__main__":
    debug_zero_data_issue()
